/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package elgamal;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author morfant
 */
public class ElGamalFrame extends javax.swing.JFrame {

    /**
     * Creates new form ElGamalFrame
     */
    public ElGamalFrame() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        textAreaWithTextForSignature = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        textAreaWithResult = new javax.swing.JTextArea();
        jLabel2 = new javax.swing.JLabel();
        buttonSign = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("ElGamal");

        jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        textAreaWithTextForSignature.setColumns(20);
        textAreaWithTextForSignature.setLineWrap(true);
        textAreaWithTextForSignature.setRows(5);
        textAreaWithTextForSignature.setWrapStyleWord(true);
        jScrollPane1.setViewportView(textAreaWithTextForSignature);

        jLabel1.setText("Текст для подписи");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 636, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 112, Short.MAX_VALUE)
                .addContainerGap())
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));

        textAreaWithResult.setColumns(20);
        textAreaWithResult.setLineWrap(true);
        textAreaWithResult.setRows(5);
        textAreaWithResult.setWrapStyleWord(true);
        jScrollPane2.setViewportView(textAreaWithResult);

        jLabel2.setText("Результат");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 192, Short.MAX_VALUE)
                .addContainerGap())
        );

        buttonSign.setText("Подписать");
        buttonSign.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSignActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(buttonSign)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(buttonSign)
                .addGap(18, 18, 18)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void buttonSignActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSignActionPerformed
        singText();
    }//GEN-LAST:event_buttonSignActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ElGamalFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ElGamalFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ElGamalFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ElGamalFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ElGamalFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonSign;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea textAreaWithResult;
    private javax.swing.JTextArea textAreaWithTextForSignature;
    // End of variables declaration//GEN-END:variables
    public static final BigInteger TWO = new BigInteger("2");
    public static final BigInteger MINUS_ONE = new BigInteger("-1");

    public static BigInteger powBigIntegerWithMod(BigInteger base, BigInteger degree, BigInteger mod) {

        BigInteger localBase = new BigInteger(base.toString());
        BigInteger localDegree = new BigInteger(degree.toString());

        BigInteger value = new BigInteger("1");

        while (!localDegree.equals(BigInteger.ZERO)) {
            if (!localDegree.mod(TWO).equals(BigInteger.ZERO)) {
                value = value.multiply(localBase).mod(mod);
                localDegree = localDegree.add(MINUS_ONE);
            }
            localDegree = localDegree.divide(TWO);
            localBase = localBase.pow(2).mod(mod);
        }
        return value;
    }

    public static boolean isCoprimeSimple(BigInteger a, BigInteger b) {

        BigInteger c;
        while (!b.equals(BigInteger.ZERO)) {
            c = a.mod(b);
            a = b;
            b = c;
        }

        return a.equals(BigInteger.ONE);

    }

    private void singText() {
        String text = textAreaWithTextForSignature.getText();
//
//        System.out.println("[" + text + "]");

        try {

            int base = 512;

            Random random = new Random(System.currentTimeMillis());

            BigInteger p = BigInteger.probablePrime(base, random);
            BigInteger pMinusOne = p.add(MINUS_ONE);

            BigInteger g;
            do {
                g = BigInteger.probablePrime(base, random);
            } while (g.compareTo(p) != -1);

            BigInteger x;
            do {
                x = new BigInteger(base, random);
            } while (x.compareTo(p) != -1);

            BigInteger y = powBigIntegerWithMod(g, x, p);

            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(text.getBytes());
            BigInteger m = new BigInteger(messageDigest.digest());
            if (m.compareTo(BigInteger.ZERO) == -1) {
                m = m.negate();
            }

            BigInteger k;
            do {
                k = new BigInteger(base, random);
            } while (!isCoprimeSimple(pMinusOne, k));

            BigInteger r = powBigIntegerWithMod(g, k, p);

            BigInteger s = (m.add(x.multiply(r).negate())).multiply(k.modInverse(pMinusOne)).mod(pMinusOne);

            textAreaWithResult.replaceRange("", 0, textAreaWithResult.getText().length());

            textAreaWithResult.append("p = \n" + p + "\n");
            textAreaWithResult.append("p-1 =  \n" + pMinusOne + "\n");
            textAreaWithResult.append("g =  \n" + g + "\n");
            textAreaWithResult.append("x =  \n" + x + "\n");
            textAreaWithResult.append("y =  \n" + y + "\n");
            textAreaWithResult.append("m =  \n" + m + "\n");
            textAreaWithResult.append("r =  \n" + r + "\n");
            textAreaWithResult.append("s =  \n" + s + "\n");

            BigInteger gPowM = powBigIntegerWithMod(g, m, p);
            BigInteger gPowROnRPowS = powBigIntegerWithMod(y, r, p).multiply(powBigIntegerWithMod(r, s, p)).mod(p);

            textAreaWithResult.append("g^m = \n" + gPowM + "\n");
            textAreaWithResult.append("y^r*r^s = \n" + gPowROnRPowS + "\n");
            textAreaWithResult.append("Подписи совпадают = " + gPowM.equals(gPowROnRPowS) + "\n");



//            System.out.println("p =  \n" + p);
//            System.out.println("p-1 =  \n" + pMinusOne);
//            System.out.println("g =  \n" + g);
//            System.out.println("x =  \n" + x);
//            System.out.println("y =  \n" + y);
//            System.out.println("m =  \n" + m);
//            System.out.println("r =  \n" + r);
//            System.out.println("s =  \n" + s);
//            
//            System.out.println("g^m = \n" + powBigIntegerWithMod(g, m, p));
//            
//            System.out.println("y^r*r^s = \n" + powBigIntegerWithMod(y, r, p).multiply(powBigIntegerWithMod(r, s, p)).mod(p));

        } catch (NoSuchAlgorithmException ex) {
          
        }
    }

    private void printErrorMessage(Exception exc) {
        JOptionPane.showMessageDialog(null, exc.getMessage(), "Error",
                JOptionPane.ERROR_MESSAGE);
    }
}
